package ex.hql.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ex.hql.mapper.AdminMapper;
import ex.hql.mapper.AdminRoleMapper;
import ex.hql.pojo.*;
import ex.hql.service.IAdminService;
import ex.hql.utils.AdminUtils;
import ex.hql.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hql
 * @since 2021-08-19
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Qualifier("myUserDetailService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Value("${jwt.tokenHead}")
    private String tokenHeader;

    /**
     * 登录之后返回token
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if(ObjectUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码输入错误,请重新输入!");
        }

        //登入
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(userDetails==null||!passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或者密码不正确");
        }
        if(!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，请联系管理员");
        }
        //更新登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.generatorToken(userDetails);
        Map<String,String> tokenMap=new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHeader",tokenHeader);
        return RespBean.success("登录成功",tokenMap);
    }


    /**
     * 根据用户名获取用户  ps:缺少健壮性判断
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        return getBaseMapper().selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }


    /**
     * 根据用户id查对应角色权限
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return getBaseMapper().getRoles(adminId);
    }


    /**
     * 获取所有操作员
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return getBaseMapper().getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
    }

    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        Integer result = adminRoleMapper.updateAdminRole(adminId, rids);
        if(rids.length==result){
            return RespBean.success("更新成功！");
        }
        else {
            return RespBean.error("更新失败！");
        }
    }

    /**
     * 更新用户密码
     * @param oldPass
     * @param pass
     * @param id
     * @return
     */
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer id) {
        Admin admin=getBaseMapper().selectById(id);
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        if (encoder.matches(oldPass,admin.getPassword())) {
            admin.setPassword(encoder.encode(pass));
            int result = getBaseMapper().updateById(admin);
            if(1==result){
                return RespBean.success("更新密码成功！");
            }else {
                return RespBean.error("更新密码失败！");
            }
        }
        return null;
    }


    /**
     * 更新用户头像
     * @param url
     * @param id
     * @param authentication
     * @return
     */
    @Override
    public RespBean updateAdminuserFace(String url, Integer id, Authentication authentication) {
        Admin admin = getBaseMapper().selectById(id);
        admin.setUserface(url);
        int result = getBaseMapper().updateById(admin);
        if(1==result){
            Admin principal = ((Admin) authentication.getPrincipal());
            principal.setUserface(url);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功！",url);
        }
    return RespBean.error("更新失败！");

    }
}
